#!/bin/bash
#
# Caddy Web Server Installer
# https://github.com/sayem314/Caddy-Web-Server-Installer
#

# Do not change any value after installation
caddypath="/opt/caddyserver" # folder where caddyserver will be kept
caddywww="/var/caddywww" # folder where public files should be
caddyfile="/etc/Caddyfile" # caddy web server configuration file
caddylog="/var/log/caddy" # folder where logs will be written
caddyuser="caddy" # user under caddy is gonna be running

# Load and replace above variable if Caddy.conf exists
[[ -e /etc/Caddy.conf ]] && source /etc/Caddy.conf

# Global config
caddyname="Caddy Web Server"
cwsiv="v6.0 (25 Oct 2017)"
bashname=$(basename $BASH_SOURCE)
pids=$(pgrep -nf $caddypath/caddy)

# working directory
cd /opt || echo "Oops! /opt doesn't exist."

about () {
	echo ""
	echo "  ========================================================= "
	echo "  \             Caddy Web Server Installer                / "
	echo "  \                  $cwsiv                   / "
	echo "  \             Created by Sayem Chowdhury                / "
	echo "  \             Caddy Web: Caddyserver.com                / "
	echo "  ========================================================= "
	echo ""
}

howto () {
	echo "  Welcome!"
	echo "  run $(tput setaf 3)$bashname help $(tput sgr0) for help"
	echo ""
}

prms () {
	echo ""
	echo "  $bashname start          - Start $caddyname."
	echo "  $bashname stop           - Stop/Shutdown $caddyname."
	echo "  $bashname reload         - Reload $caddyname."
	echo "  $bashname restart        - Restart $caddyname."
	echo "  $bashname status         - Check $caddyname is running or not"; echo "                         or just run '$bashname'."
	echo "  $bashname install        - Install $caddyname on fresh OS."
	echo "  $bashname install-naked  - Install only $caddyname and no prompt."
	echo "  $bashname edit           - Edit Caddyfile using nano or default editor." 
	echo "  $bashname service        - Make $caddyname start on boot (upstart/systemd)."; echo "                         Not required because we install service on install."
	echo "  $bashname update         - Update $caddyname."
	echo "  $bashname delete         - Uninstall $caddyname and data."; echo "                         We would prompt you if you want to keep data."
	echo "  $bashname version        - Print version information."
	echo "  $bashname about          - About $caddyname Installer."
	echo ""
}

isinstalled () {
	# check if caddy is installed or return error code 1
	if [[ ! -x $caddypath/caddy ]]; then
		echo; echo "  Caddy is not installed.";
		echo "  run $(tput setaf 3)$bashname install$(tput sgr0) to install $caddyname";
		echo; return 1
	fi
}

startcaddy () {
	# exit if caddy is not installed
	isinstalled || exit 1

	# create process id folder if necessary
	caddypid="/var/run/caddy"
	if [[ ! -f $caddypid ]]; then
		mkdir -p $caddypid || ( echo "  error creating folder $caddypid" 
		echo "  try running with: sudo $bashname start" && exit )
		chown $caddyuser $caddypid
	fi

	# Detect if running or start
	pids=$(pgrep -nf $caddypath/caddy)
	if [ -z "$pids" ] ; then
		echo -n "  Starting $caddyname..."
		if [[ -e /etc/init/caddy.conf || -e /etc/systemd/system/caddy.service ]]; then
			# If service exist use service
			hash service 2>/dev/null && service caddy start || systemctl start caddy
		else
			sudo -H -u $caddyuser $caddypath/caddy -conf="$caddyfile" -quiet=true -pidfile=$caddypid/caddy.pid &
		fi
		sleep 1
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"

		sleep 1
		# restart or reload php for smooth environment
		hash php 2>/dev/null && restartphpfpm;
		pids=$(pgrep -nf $caddypath/caddy); caddystatus;
	else
		echo ""
		echo "  $caddyname is already $(tput setaf 2)running$(tput sgr0) on: $pids (PID)"
		echo ""
	fi
}

stopcaddy () {
	pids=$(pgrep -nf $caddypath/caddy)
	if [ -z "$pids" ] ; then
		echo ""
		echo "  $caddyname is $(tput setaf 1)NOT running$(tput sgr0)"
		echo ""
	else
		secs=$(ps -p $pids -oetime= | tr '-' ':' | awk -F: '{ total=0; m=1; } { for (i=0; i < NF; i++) {total += $(NF-i)*m; m *= i >= 2 ? 24 : 60 }} {print total}')
		echo -n "  Shutting down $caddyname..."
		# Wait if Caddy uptime is less than 5 seconds
		if [[ $secs -lt 5 ]]; then
			sleep 4
		fi
		if [[ -e /etc/init/caddy.conf || -e /etc/systemd/system/caddy.service ]]; then
			# Most arch based linux don't have service
			hash service 2>/dev/null && service caddy stop || systemctl stop caddy
		else
			kill $pids
		fi
		sleep 1
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
	fi
}

reloadcaddy () {
	if [ -z "$pids" ] ; then
		echo ""
		echo "  $caddyname is $(tput setaf 1)NOT running$(tput sgr0)"
		echo "  run $(tput setaf 3)$bashname start$(tput sgr0) to start Caddy"
		echo ""
	else
		echo ""
		echo -n "  Reloading $caddyname..."
		if [[ -e /etc/init/caddy.conf || -e /etc/systemd/system/caddy.service ]]; then
			# Headless server should have service
			hash service 2>/dev/null && service caddy reload || systemctl reload caddy
		else
			kill -USR1 $pids
		fi
		sleep 2
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
		echo ""
		echo "  To restart, use $(tput setaf 6)$bashname restart$(tput sgr0)"
		echo "  Refresh your browser at least 3 times to take affect"
		echo ""
	fi
}

restartphpfpm () {
	phpvalue;
	# Ubuntu
	if [[ -e "$ubuntuphp5fpm" ]]; then
	service php5-fpm restart &>/dev/null

	# CentOS
	elif [[ -e "$centosphpfpm" || -e "$centosphpfpm2" ]]; then
	service php-fpm restart &>/dev/null
	
	# PHP 7
	elif [[ -e "$phpfpm7" ]]; then
	/etc/init.d/php7.0-fpm reload &>/dev/null
	fi
}

caddystatus () {
	# Check if Caddy is installed or not
	isinstalled || exit 1

	# Detect Caddy process
	if [ -z "$pids" ] ; then
		echo ""
		echo "  $caddyname is $(tput setaf 1)NOT running$(tput sgr0)"
		echo ""
	else
		caddymemusage=$(ps axo rss,comm,pid | grep $pids | awk '{$1/=1024;printf "%.0fMB\t",$1}{print $2}' | awk '{print $1}')
		secs=$(ps -p $pids -oetime= | tr '-' ':' | awk -F: '{ total=0; m=1; } { for (i=0; i < NF; i++) {total += $(NF-i)*m; m *= i >= 2 ? 24 : 60 }} {print total}')
		if [[ $secs -lt 120 ]]; then
			caddyuptime="$secs seconds"
		elif [[ $secs -lt 3600 ]]; then
			caddyuptime=$(printf '%d minutes %d seconds\n' $(($secs%3600/60)) $(($secs%60)))
		elif [[ $secs -lt 86400 ]]; then
			caddyuptime=$(printf '%d hrs %d min %d sec\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60)))
		else
			caddyuptime=$(echo $((secs/86400))" days, "$(date -d "1970-01-01 + $secs seconds" "+%H hrs %M min %S sec"))
		fi
		echo ""
		echo "  $caddyname is $(tput setaf 2)running$(tput sgr0)"
		echo "  Caddy (PID: $pids) is using $caddymemusage RAM"
		echo "  System available RAM $(free -h | grep Mem: | awk '{print $7}')B"
		echo "  Uptime - $caddyuptime"
		echo ""
	fi
}

amiroot () {
	if [[ "$EUID" -ne 0 ]]; then
		echo "  Sorry, you need to run this as root"
		echo "  Try running with command 'sudo'"
		exit
	fi
}

getcaddy () {
	# Detect architecture. We only support linux.
	if [ -n "$(uname -m | grep 64)" ]; then
		cpubits="amd64"
		cpubitsname="64bit..."
	elif [ -n "$(uname -m | grep 86)" ]; then
		cpubits="386"
		cpubitsname="32bit..."
	elif [ -n "$(uname -m | grep armv5)" ]; then
		cpubits="arm5"
		cpubitsname="ARM 5..."
	elif [ -n "$(uname -m | grep armv6l)" ]; then
		cpubits="arm6"
		cpubitsname="ARM 6..."
	elif [ -n "$(uname -m | grep armv7l)" ]; then
		cpubits="arm7"
		cpubitsname="ARM 7..."
	else
		echo; echo "  unsupported or unknown architecture";
		echo; exit;
	fi

	# Downloading Caddy
	isupdate="$1"
	nocert="--no-check-certificate"
	if [[ $isupdate == "update" ]]; then
		caddyversion=$($caddypath/caddy -version | awk '{print}')
		echo ""; echo "  Found $caddyversion";
	fi

	# Check if plugin should be installed
	if [[ ! $plugin == "" ]]; then
		cpubits="$cpubits?plugins=$plugin&license=personal"
		echo -n "  Downloading $caddyname with plugin ($plugin) for $cpubitsname" # Caddy linux
	else
		cpubits="$cpubits?license=personal"
		echo -n "  Downloading $caddyname for $cpubitsname" # Caddy linux
	fi

	# Star downloading caddy now
	if ! wget -q $nocert "https://caddyserver.com/download/linux/$cpubits" -O "caddy_linux_custom.tar.gz"; then
		echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
		echo ""
		echo "  Error: Cannot download Caddy binary!"
		echo "  https://caddyserver.com/download/linux/$cpubits"
		exit 1
	fi
	echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
}

installcaddy () {
	# Detetcting if Caddy is installed or not
	echo ""
	if [[ -e "$caddypath/caddy" ]]; then
		echo "  $caddyname is already installed on"
		echo "  $caddypath/caddy"
		echo; exit;
	fi

	# Download caddy
	getcaddy;

	# Creating folders
	mkdir -p $caddypath
	mkdir -p $caddylog
	
	# Extract Caddy to appropriate folder
	echo -n "  Extracting $caddyname to $caddypath..."
	if ! tar xzf caddy_linux_custom.tar.gz -C $caddypath; then
		echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
		echo ""
		echo "  Error: Cannot extract 'caddy_linux_custom.tar.gz'"
		echo "  Abort."
		exit 1
	fi
	echo " $(tput setaf 2)[DONE]$(tput sgr0)"
	rm -f caddy_linux_custom.tar.gz # Deleting Caddy archive
	echo ""

	# Skip php installation on arch-linux and naked install
	# Php installation support for arch-linux will be implemented later
	if [[ ! $1 == naked ]]; then
		hash pacman 2>/dev/null || installphp
	fi

	# Creating non-root user
	if id -u $caddyuser >/dev/null 2>&1; then
		echo "  User '$caddyuser' already exists. Skipped!"
	else
		echo -n "  Creating user '$caddyuser'..."
		useradd -r -d $caddypath -s /bin/false $caddyuser &> /dev/null
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
    fi
	chown -R $caddyuser $caddypath
	chown -R $caddyuser $caddylog

	# Port setup
	echo -n "  Binding port using setcap..."
	if hash setcap 2>/dev/null; then
		setcap cap_net_bind_service=+ep $caddypath/caddy &>/dev/null && echo "  [$(tput setaf 2)DONE$(tput sgr0)]" || echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
	elif hash apt-get 2>/dev/null; then
		apt-get install libcap2-bin -y &>/dev/null
		setcap cap_net_bind_service=+ep $caddypath/caddy &>/dev/null && echo "  [$(tput setaf 2)DONE$(tput sgr0)]" || echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
	else
		echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
	fi

	# Show succes message on naked install
	if [[ $1 == naked ]]; then
		echo ""
		echo "  Installed $caddyname to $caddypath"
		echo ""
	fi
}

updatecaddy () {
	# Detetcting Caddy installed or not
	isinstalled || exit 1

	echo;

	# Check if there is newer version available
	caddyversion=$($caddypath/caddy -version | awk '{print}' | sed 's/[^0-9]*//g' | sed 's/^0*//')
	CADDYV=$(wget -qO- https://api.github.com/repos/mholt/caddy/releases/latest | grep tag_name | sed 's/[^0-9]*//g' | sed 's/^0*//')
	if [[ ! $CADDYV -gt $caddyversion ]]; then
		echo "  Looks like you already have latest version installed."
		sleep 0.1
		echo "  Abort.";
		sleep 0.1
		exit;
	fi

	# Download caddy
	getcaddy update;
	sleep 0.1

	# Stop current process if found
	if [ ! -z "$pids" ] ; then
		echo ""
		echo "  Found Caddy is running!"
		stopcaddy;
	fi
	# Delete Caddy folder
	echo -n "  Removing current $caddyname from $caddypath"
	sleep 0.2
	rm -rf $caddypath/*
	echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
	sleep 0.1

	# Extract Caddy to appropriate folder
	echo -n "  Extracting $caddyname to $caddypath..."
	if ! tar xzf caddy_linux_custom.tar.gz -C $caddypath; then
		echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
		echo ""
		echo "  Error: Cannot extract 'caddy_linux_custom.tar.gz'"
		echo "  Abort."
		exit 1
	fi
	echo " $(tput setaf 2)[DONE]$(tput sgr0)"

	# Granting owner access and required permission
	if id -u $caddyuser >/dev/null 2>&1; then
		chown -R $caddyuser $caddypath
	fi

	# Port setup
	hash setcap 2>/dev/null && setcap cap_net_bind_service=+ep $caddypath/caddy &>/dev/null

	# Removing caddy archive and printing info
	echo $(date +%s) > $caddypath/update.check
	rm -f caddy_linux_custom.tar.gz # Deleting Caddy archive
	caddyversion=$($caddypath/caddy -version | awk '{print}')
	echo; echo "  Updated to $caddyversion"; echo;
}


installphp () {
	if [[ -e "$caddypath" ]] ; then
		read -r -p "  Are you gonna run php site? [y/N]: " -e -i y option
		case $option in
		[yY][eE][sS]|[yY])
			echo -n "  Installing required php files..."

			# Detecting apt-get/yum
			if hash apt-get 2>/dev/null; then
				CODENAME=$(cat /etc/*-release | grep "VERSION_ID=" | cut -f1 -d'.'| cut -f2 -d'"')
				DEBIAN9=$(lsb_release -i | awk 'NF{ print $NF }')
				# If debian 9 or above select php7
				if [[ $DEBIAN9 == Debian ]]; then
					DEBIAN9V=$(lsb_release -r | awk 'NF{ print $NF }' | cut -f1 -d'.')
					CODENAME="0"
				fi
			fi

			# Setup PHP
			if [[ $CODENAME -gt 15 ]] || [[ $DEBIAN9V -gt 8 ]]; then
				PHP="php7.0"
			else
				PHP="php5"
			fi

			# Install PHP
			if hash yum 2>/dev/null; then
				yum update -y &>/dev/null && yum install sed php-fpm php-cli php-curl curl sudo -y &>/dev/null
				echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
				echo "  Installed 'php-fpm php-cli php-curl curl sudo'"
				fixphpfpm;
 			elif hash apt-get 2>/dev/null; then
				apt-get update -y &>/dev/null && apt-get install sed $PHP-fpm $PHP-cli $PHP-curl curl sudo -y &>/dev/null
				echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
				echo "  Installed '$PHP-fpm $PHP-cli $PHP-curl curl sudo'"
				fixphpfpm;
			else
				echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
 			fi
 			;;
		*)
			echo "  PHP installation skipped!"
			;;
		esac
	else
		echo "  Looks like Caddy was not installed!"
	fi
}

phpvalue () {
	ubuntuphp5fpm="/etc/php5/fpm/pool.d/www.conf"
	centosphpfpm="/etc/php/fpm/pool.d/www.conf"
	centosphpfpm2="/etc/php-fpm.d/www.conf"
	phpfpm7="/etc/php/7.0/fpm/pool.d/www.conf"
}

fixphpfpm () {
	phpvalue;
	phpuser=$1
	if [[ $phpuser == "" ]]; then
		phpuser=$caddyuser
	fi
	# Detect php5-fpm or php-fpm
	echo -n "  Fixing php sock issue..."
	#Ubuntu
	if [[ -e "$ubuntuphp5fpm" ]] ; then
		sed -i "s@user = .*@user = $phpuser@g" $ubuntuphp5fpm
		sed -i "s@group = .*@group = $phpuser@g" $ubuntuphp5fpm
		sed -i 's/listen = .*/listen = 127.0.0.1:9000/g' $ubuntuphp5fpm
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"

	# CentOS
	elif [[ -e "$centosphpfpm" ]] ; then
		sed -i "s@user = .*@user = $phpuser@g" $centosphpfpm
		sed -i "s@group = .*@group = $phpuser@g" $centosphpfpm
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"

	# CentOS 2
	elif [[ -e "$centosphpfpm2" ]] ; then
		sed -i "s@user = .*@user = $phpuser@g" $centosphpfpm2
		sed -i "s@group = .*@group = $phpuser@g" $centosphpfpm2
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"

	# PHP 7
	elif [[ -e "$phpfpm7" ]] ; then
		sed -i "s@user = .*@user = $phpuser@g" $phpfpm7
		sed -i "s@group = .*@group = $phpuser@g" $phpfpm7
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
	
	else
		echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
		echo "  php not found!"
		echo ""
	fi
}

caddyfile () {
	phpvalue;
	# Ubuntu
	if [[ -e "$ubuntuphp5fpm" ]] ; then
	phpsock=$(cat $ubuntuphp5fpm | grep "listen = *" | cut -c 10-)
	
	# CentOS
	elif [[ -e "$centosphpfpm" ]] ; then
	phpsock=$(cat $centosphpfpm | grep "listen = *" | cut -c 10-)

	# CentOS 2
	elif [[ -e "$centosphpfpm2" ]] ; then
	phpsock=$(cat $centosphpfpm2 | grep "listen = *" | cut -c 10-)

	# PHP 7
	elif [[ -e "$phpfpm7" ]] ; then
	sed -i 's/listen = .*/listen = 127.0.0.1:9000/g' $phpfpm7
	phpsock=$(cat $phpfpm7 | grep "listen = *" | cut -c 10-)
	
	else
	phpsock="127.0.0.1:9000"
	fi

	# Check if Caddyfile exist
	# Generate Caddyfile
	if [[ ! -e $caddyfile ]]; then
		echo ""
		echo "  Enter your domain name"
		echo "  Seperated by comma"
		read -p "  Domain name: " domainname
		echo ""
		# Check if gonna run locally
		if [[ $domainname == "localhost" || $domainname == "localhost:*" || $domainname == "127.0.0*" || $domainname == "192.168*" ]]; then
			echo "  SSL is disabled on non-production server."
		else
			echo "  Enter your email for automated ssl"
			read -p "  Email: " domainmail
			until [[ "$domainmail" == *@*.* || "$domainmail" == off ]]; do
				echo ""
				echo "  Invalid email"
				echo "  Type $(tput setaf 3)off$(tput sgr0) if you don't want https"
				read -p "  Email: " domainmail
			done
		fi

		echo "$domainname {
	root $caddywww
	gzip
	tls $domainmail
	log $caddylog/access.log
	errors $caddylog/error.log
	fastcgi / $phpsock php
}
" >> $caddyfile

		echo ""
		echo "  $caddyfile created"
	else
		echo "  $caddyfile found. Skipped! "
	fi

	# Check if caddywww exist
	if [[ ! -e $caddywww ]]; then
		mkdir -p $caddywww
	fi

	# Generate example html
	if [[ ! -e $caddywww/index.html ]]; then
		echo "<TITLE>Caddy Default Page</TITLE>

<h1><font color="green">It works!</font></h1>

<h3><font color="grey">This is the default welcome page used to test the correct operation of the Caddy web server after installation via Caddy Web Server Installer.</font></h3>

<h3><font color="grey">If you can read this page, it means that the Caddy web server installed at this site is working properly.<br>
You should <font color="#D03C3C">replace this file</font>
(located at <tt>$caddywww/index.html</tt>) before continuing to operate your server.</font></h3>
</hr>
<h3><font color="grey">If you are a normal user of this web site and don't know what this page is about, this probably means that the site is currently unavailable due to maintenance.</font></h3>" >> $caddywww/index.html
		echo "  index file created"
		echo "  $caddywww/index.html"
	else
		echo "  index.html found. Skipped!"
	fi

	# phpinfo
	if [[ ! -e $caddywww/info.php ]]; then
		echo "<?php phpinfo(); ?>" >> $caddywww/info.php
		echo ""
		echo "  PHP-info file created"
		echo "  $caddywww/info.php"
	fi

	chown -R $caddyuser $caddywww

	echo ""
	echo "  Done. Caddy has been installed :)"
	echo "  Run $(tput setaf 3)$bashname start$(tput sgr0) to start $caddyname"
	echo ""

}

makeservice () {
if [[ -e /etc/systemd/system/caddy.service || -e /etc/init.d/caddy.sh ]]; then
	echo "  Service already exists. Skipped!"
else
	nocert="--no-check-certificate"
	init=$(cat /proc/1/comm)
	echo -n "  Creating startup service..."
	if [ "$init" == 'systemd' ]; then
		MAIN="$"
		MAINPID="MAINPID"
		rm -f /etc/systemd/system/caddy.service
		cat <<EOF > /etc/systemd/system/caddy.service
[Unit]
Description=Caddy HTTP/2 web server
Documentation=https://caddyserver.com/docs
After=network-online.target
Requires=network-online.target

[Service]
User=$caddyuser
StartLimitInterval=86400
StartLimitBurst=5
LimitNOFILE=16535
ExecStart=$caddypath/caddy -conf=$caddyfile -quiet=true -pidfile=/var/run/caddy/caddy.pid
ExecReload=/bin/kill -USR1 $MAIN$MAINPID
ExecStop=/bin/kill $MAIN$MAINPID
PIDFile=/var/run/caddy/caddy.pid

[Install]
WantedBy=multi-user.target
EOF
		chmod 0644 /etc/systemd/system/caddy.service
		echo "  $(tput setaf 2)DONE$(tput sgr0)"
		echo ""
		systemctl daemon-reload
		systemctl enable caddy
	else
		# Download
		wget -q $nocert "https://raw.githubusercontent.com/sayem314/Caddy-Web-Server-Installer/master/php-fpm/runcaddy.sh" -O "/etc/init.d/caddy.sh"
		chmod +x /etc/init.d/caddy.sh
		# Enable
		if hash yum 2>/dev/null; then
			chkconfig caddy.sh on
			echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
		elif hash apt-get 2>/dev/null; then
			echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
			update-rc.d caddy.sh defaults
		else
			echo "  [$(tput setaf 1)FAILED$(tput sgr0)]"
		fi
	fi
fi
}

deletecaddy () {
	if [[ -e  "$caddypath" ]] ; then
		echo ""
		echo "  Are you sure you want to uninstall Caddy web server? [y/N]"
		read -p "  Select an option: " option
		case $option in
		[yY][eE][sS]|[yY])
			# Stop caddy if running
			if [ ! -z "$pids" ] ; then
				echo "  Found Caddy is running!"
				stopcaddy;
				sleep 2
			fi
			sleep 1

			# Disable and remove startup script if exist
			removeservice;

			# Remove Caddy web server folder, usually on /opt/caddyserver.
			rm -rf $caddypath &>/dev/null

			# Backup Caddyfile if exists, usually on /etc/Caddyfile.
			if [[ -e $caddyfile ]]; then
				cp $caddyfile $caddyfile.bak
				echo "  Backup of current Caddyfile saved to $caddyfile.bak"
			fi

			# Now remove Caddyfile
			rm -f $caddyfile &>/dev/null

			# Prompt if data should be removed
			if [[ -d  "$caddywww" ]]; then
				echo "  $caddyname has been deleted."
				deletecaddydata;
			else
				# remove caddy user
				if [[ ! $caddyuser == $(whoami) ]]; then
					if id -u $caddyuser >/dev/null 2>&1; then
						hash php 2>/dev/null && fixphpfpm www-data;
						restartphpfpm;
						userdel $caddyuser # delete caddy user
						echo "  $caddyname and Caddy user '$caddyuser' has been deleted."
					fi
				fi
			fi
			echo ""
			exit
			;;
		[nN][oO]|[nN])
			echo "  Abort."
			exit;
			;;
		*) echo ""; echo "  Incorrect input, exiting! "; exit;;
		esac
	else
		echo ""
		echo "  Looks like Caddy is not installed!"
	fi
	echo ""
}

removeservice () {
	# Disable and remove startup script if exist
	if [[ -e /etc/init/caddy.conf || -e /etc/systemd/system/caddy.service ]]; then
		init=$(cat /proc/1/comm)
		echo -n "  Removing startup service..."
		if [ "$init" == 'systemd' ]; then
			systemctl disable caddy &>/dev/null
			rm -f /etc/systemd/system/caddy.service &>/dev/null
		elif [ "$init" == 'init' ]; then
			update-rc.d -f caddy.sh remove
			rm -f /etc/init/caddy.conf &>/dev/null
		fi
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
	fi
}

deletecaddydata () {
	totalsize=$(du -sh $caddywww)
	totalfiles=$(find $caddywww -type f | wc -l)
	echo ""
	echo "  Would you also like to delete data?"
	echo "  Size: $totalsize (Files: $totalfiles)"
	read -r -p "  Select an option [y/N]: " option
	echo ""
	case $option in
	[yY][eE][sS]|[yY])
		echo -n "  Deleting $caddywww (data)..."
		sleep 2
		rm -rf $caddywww # deleting caddy html folder
		echo "  [$(tput setaf 2)DONE$(tput sgr0)]"
		# remove caddy user too if exists
		if [[ ! $caddyuser == $(whoami) ]]; then
			if id -u $caddyuser >/dev/null 2>&1; then
				hash php 2>/dev/null && fixphpfpm www-data;
				hash php 2>/dev/null && restartphpfpm;
				userdel $caddyuser # delete caddy user
				echo "  Caddy user '$caddyuser' has been deleted too."
			fi
		fi
		;;
	*)
		echo "  Removing $caddywww (data)... [$(tput setaf 5)Skipped$(tput sgr0)]"
		;;
	esac
}

versioninfo () {
	echo ""
	if [[ -e $caddypath/caddy ]]; then
		caddyversion=$($caddypath/caddy -version | awk '{print $2}')
		echo "  $caddyname $caddyversion"
	else
		echo "  $caddyname is not installed."
	fi
	echo "  Caddy Web Server Installer - $cwsiv"
	if hash php 2>/dev/null; then
		echo "  $(php -v | grep cli)"
	fi
	echo ""
}

# Edit Caddyfile using nano or default editor
editcaddyfile (){
	if hash nano 2>/dev/null; then
		echo " opening $caddyfile using nano"
		nano $caddyfile
	elif hash editor 2>/dev/null; then
		editor $caddyfile
	else
		echo "  error: please manually edit files"
		echo "  $caddyfile"
 	fi
}

checkforupdate () {
	# Check if there is newer version available
	# Currenly only check caddyserver not this script
	caddyversion=$($caddypath/caddy -version | awk '{print}' | sed 's/[^0-9]*//g' | sed 's/^0*//')
	CADDYV=$(wget -qO- https://api.github.com/repos/mholt/caddy/releases/latest | grep tag_name | sed 's/[^0-9]*//g' | sed 's/^0*//')
	if [[ $CADDYV -gt $caddyversion ]]; then
		echo ""
		echo "  $(tput setaf 1)NOTICE:$(tput sgr0)"
		echo "  There is an update available of $caddyname"
		echo "  run $(tput setaf 3)$bashname update$(tput sgr0) to update"
		echo ""
	else
		[[ $CADDYV == "" ]] || echo $(date +%s) > $caddypath/update.check || sudo echo $(date +%s) > $caddypath/update.check
	fi
}

# See how we were called.
case $1 in
	'-start'|'--start'|'start'|'startcaddy' )
		startcaddy;;
	'-stop'|'--stop'|'stop'|'stopcaddy' )
		stopcaddy;;
	'-reload'|'--reload'|'reload'|'reloadcaddy' )
		reloadcaddy;;
	'-restart'|'--restart'|'restart' )
		stopcaddy; sleep 2; startcaddy;;
	'-status'|'--status'|'status'|'caddystatus' )
		caddystatus;;
	'-install'|'--install'|'install' )
		amiroot; plugin="$2"; installcaddy; makeservice; caddyfile;;
	'-install-naked'|'--install-naked'|'install-naked' )
		amiroot; plugin="$2"; installcaddy naked;;
	'-update'|'--update'|'update'|'updatecaddy' )
		amiroot; plugin="$2"; updatecaddy; caddyfile;;
	'-fixphp'|'--fixphp'|'fixphp'|'fixphpfpm' )
		amiroot; fixphpfpm;;
	'-installphp'|'--installphp'|'installphp' )
		amiroot; installphp;;
	'-edit'|'edit'|'editcaddyfile' )
		amiroot; editcaddyfile;;
	'-service'|'--service'|'service'|'makeservice' )
		amiroot; makeservice;;
	'-del'|'delete'|'--delete'|'-rm'|'deletecaddy' )
		amiroot; deletecaddy;;
	'delete-service'|'--delete-service'|'remove-startup'|'--remove-startup' )
		amiroot; removeservice;;
	'-about'|'about'|'--about' )
		about;;
	'-h'|'help'|'-help'|'--help' )
		prms;;
	'-v'|'version'|'-version'|'--version'|'versioninfo'|'-V' )
		versioninfo;;
	*)
		caddystatus; howto;;
esac

# check updates every 72hrs
if [[ -e "$caddypath/caddy" ]]; then
	# Create update.check file if not exist
	if [[ ! -e $caddypath/update.check ]]; then
		echo $(date +%s) > $caddypath/update.check
		chmod 777 $caddypath/update.check
	elif [[ -e $caddypath/update.check  ]]; then
		currentdays="$(date +%s)"
		lastcheckdays=$(cat $caddypath/update.check)
		updatedays="$(($currentdays - $lastcheckdays))"
		# if more than 72hrs execute update check
		if [[ $updatedays -gt 259200 ]]; then
			checkforupdate;
		fi
	fi
fi

# exit now!
exit 0
